package com.statistics.util;

import com.alibaba.fastjson2.JSONObject;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

public class ScienceExchangeExportUtils {

    public static void export(HttpServletResponse response,
                              JSONObject data, String fileName) throws Exception {
        // 设置响应头
        AchExportUtils.setResponse(response, fileName);
        // 加载模板文件
        ClassPathResource resource = new ClassPathResource("/templates/" + fileName + ".xlsx");
        try (InputStream inputStream = resource.getInputStream();
             Workbook workbook = new XSSFWorkbook(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0);
            // 处理动态列表数据
            insertListData(sheet, data);
            // 写入输出流
            workbook.write(response.getOutputStream());
        }
    }

    private static void insertListData(Sheet sheet, JSONObject listData) {
        int startRow = 7;
        String[] titles = {"dispatch", "accept", "personnel", "meetingPaper", "invitedPresentations", "meeting"};
        for (int i = 0; i < titles.length; i++) {
            Row row = sheet.getRow(startRow + i);
            JSONObject jsonObject = listData.getJSONObject(titles[i]);
            row.getCell(4).setCellValue(jsonObject.getString("total"));
            row.getCell(5).setCellValue(jsonObject.getString("internal"));
            row.getCell(6).setCellValue(jsonObject.getString("foreigns"));
        }
    }

}